package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpStatus;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Fuqiang
 * @since :2023-03-22
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 系统自定义异常处理器
     */
    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException exception) {
        return new ResponseResult(exception.getStatus(), exception.getMessage());
    }


    /**
     * Validation 权限框架异常处理器
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        String msg = allErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";"));

        return new ResponseResult(400, msg);

    }

    /**
     * 全局兜底的异常处理器
     */
    @ExceptionHandler(Throwable.class)
    public ResponseResult throwableHandler(Throwable throwable) {
        log.error("全局异常处理器异常信息: {}", ExceptionUtils.getStackTrace(throwable));
        return new ResponseResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, "服务端异常,请稍后重试");
    }
}
